<?php

namespace App\Admin\Controllers;

use App\Agent;
use App\Service\MiniProgramService;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Storage;

class AgentController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '名片';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Agent());

        $grid->column('id', __('Id'));
        $grid->column('name', __('姓名'));
        $grid->column('avatar', __('头像'))->display(function ($value){
            return   Storage::url($value);
        })->image('','100','100');;
        $grid->column('qrcode','小程序码')->display(function ($value){
            return   Storage::url($value);
        })->image('','100','100');
        $grid->column('file','下载二维码')->display(function ($value){
            return Storage::url($this->qrcode);
        })->downloadable();
        $grid->column('mobile', __('手机号'));
        $grid->column('address', __('地址'));
        $grid->column('job', __('职位'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Agent::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('name', __('Name'));
        $show->field('avatar', __('Avatar'));
        $show->field('qrcode', __('Qrcode'));
        $show->field('mobile', __('Mobile'));
        $show->field('address', __('Address'));
        $show->field('job', __('Job'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Agent());

        $form->text('name', __('姓名'))->required();
        $form->image('avatar', __('头像'))->uniqueName()->required();

        $form->mobile('mobile', __('手机号'))->required();
        $form->text('address', __('地址'))->required();
        $form->text('job', __('职位'))->required();
        $form->saved(function ($from) {
            $agent=Agent::find( $from->model()->id);
            $miniProgramService=new MiniProgramService();
            $file_name = $miniProgramService->miniCode($agent->id, 'pages/index/index');
            $agent->qrcode = $file_name;
            $agent->save();
        }
        );
        return $form;
    }
}
